import { Button, message, Spin } from 'antd';
import { inject, observer } from 'mobx-react';
import { WeaTop, WeaRightMenu, WeaLocaleProvider, WeaSlideModal, WeaSearchPanel, WeaLeftRightLayout, WeaProgress, WeaNewScroll } from 'ecCom'
import { WeaTableNew, WeaForm } from 'comsMobx'
import * as  Apis from '../../../apis/govern';
import { Condition, ConditionNum } from '../list/listCondition'
import Model from '../model/index';
import ModalConfirm from '../modalConfirm/index';
import BtnType from '../../../util/btnType';
import TaskSlide from './taskSlide';
import ListLeftTree from '../governTree';
import GovernTag from '../governPoint/tag';
import GovernLight from '../governPoint/light';
import GovernBadge from '../governPoint/badge';
import { toJS } from 'mobx';
import { Common } from '../governText/text';
const common = new Common();
const getLabel = WeaLocaleProvider.getLabel;
const WeaTable = WeaTableNew.WeaTable;

@inject("taskStore")
@observer
class taskMain0 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            apisType: Apis.getMyTaskList
        }
    }
    componentDidMount = () => {
        const { taskStore } = this.props;
        //设置dataType
        // const preDataType = this.props.location.query.dataType;
        taskStore.setDataType(0);
        taskStore.getIsTreeShow();
        this.setState({
            apisType: this.props.taskStore.apisType
        });
        //初始化页面
        if (!taskStore.isSuperSearch) {
            taskStore.init({ "isSuper": "0", "isSuperPage": false, "fromSuperPage": true, "selectedTreeKey": 0, "categoryid": 0 })//19.3.8 lusx 选中树,切换菜单,数据没更新,停留在上次树的key 加"categoryid":0
        }

        jQuery(document).bind('click', function (e) {
            var e = e || window.event;
            var elem = e.target || e.srcElement;
            while (elem) {
                if (elem.className && (elem.className == 'ant-table-tbody'
                    || elem.className == 'g-task-slide' || elem.className.trim() == 'ant-modal-content'
                )) {
                    return;
                }
                elem = elem.parentNode;
            }
            taskStore.showSlideModal(false)
        });
    }
    componentWillReceiveProps(nextProps) {
        //刷新重新渲染
        if (nextProps.location.key != this.props.location.key) {
            //设置dataType
            const { taskStore } = nextProps;
            // const nextDataType = nextProps.location.query.dataType;
            taskStore.setDataType(0);
            taskStore.getIsTreeShow();
            this.setState({
                apisType: this.props.taskStore.apisType
            });
            if (!taskStore.isSuperSearch) {
                taskStore.setDoAgain(false)
                taskStore.selectedTreeKey = 0;
                //taskStore.setSelectedTreeKey(0,this.state.apisType);
                taskStore.init({ "isSuper": "0", "isSuperPage": false, "fromSuperPage": true, "selectedTreeKey": 0, "categoryid": 0 })//19.3.8 lusx 选中树,切换菜单,数据没更新,停留在上次树的key 加"categoryid":0
            }
        }
    }
    componentWillUpdate(nextProps) {
        //刷新重新渲染
        if (nextProps.location.key != this.props.location.key) {
            //设置dataType
            const { taskStore } = nextProps;
            // const nextDataType = nextProps.location.query.dataType;
            taskStore.setDataType(0);
            if (!taskStore.isSuperSearch) {
                taskStore.setDoAgain(false)
                taskStore.init({ "isSuper": "0", "isSuperPage": false, "fromSuperPage": true, "selectedTreeKey": 0, "categoryid": 0 })//19.3.8 lusx 选中树,切换菜单,数据没更新,停留在上次树的key 加"categoryid":0
            }
        }
    }
    componentDidUpdate() {
        const { taskStore } = this.props;
        jQuery(document).bind('click', function (e) {
            var e = e || window.event;
            var elem = e.target || e.srcElement;
            while (elem) {
                if (elem.className && (elem.className == 'ant-table-tbody'
                    || elem.className == 'g-task-slide' || elem.className.trim() == 'ant-modal-content'
                )) {
                    return;
                }
                elem = elem.parentNode;
            }
            taskStore.showSlideModal(false)
        });
    }
    componentWillUnmount() {
        this.props.taskStore.clear();
    }
    render() {
        const { taskStore, route: { path }, location: { pathname, search } } = this.props;
        const { status, tasklabels, form, formB, tableTaskStore, title, modelType, id, content, modelStore, dataType, setSearchPanelVisible, initSearchPanel, columnsNum ,isTreeShow,onCollapse} = taskStore;
        const { loading, showSlideModal } = status;
        const { topIcon = "icon-coms-government", iconBgcolor = "#f14a2d" } = tasklabels;
        const { visible } = this.state;
        let scrollHeight = document.body.clientHeight - 129;
        let tablescroll = document.body.clientHeight - 223.89 - 54;
        let scrollWidth = document.body.clientWidth - 468;
        // console.log("tableTaskStore",tableTaskStore,tableTaskStore.loading,(!tableTaskStore.loading && toJS(tableTaskStore).columns.length>0 ))
        return (
            <div className="g-task">
                <div className='g-task-taskMain'>
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@50drm6`} datas={this.getRightMenu()} style={{ color: "#ccc" }}>
                        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@at6arn`} loading={loading || modelStore.loading} icon={<i className={topIcon} />} iconBgcolor={iconBgcolor} title={title} >
                            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@1lltdk`}
                                leftWidth={250}
                                showLeft = {isTreeShow}
                                onCollapse={(bool) => { onCollapse(bool) }}
                                leftCom={<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@rux1sc`} height={scrollHeight}><ListLeftTree ecId={`${this && this.props && this.props.ecId || ''}_ListLeftTree@04wrlz`} apisType={this.state.apisType} treeStore={taskStore} /></WeaNewScroll>}
                            >
                                <div className='g-task-taskMain-condition g-container'>

                                    <div className="1.1" style={{ width: '50%', float: "left" }}>
                                        <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@jemlxu`} listStore={taskStore} type="task" form={form} col={2} handleChange={this.handleChange.bind(this)}></Condition>
                                    </div>
                                    <div className='1.2' style={{ float: "left" }}>
                                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fyayux`} type="primary" className="g-task-taskMain-serach" onClick={this.doSearch.bind(this)}>{getLabel(197, "搜索")}</Button>
                                    </div>
                                    <div className='1.3' style={{ float: 'left' }}>
                                        <WeaSearchPanel ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchPanel@2a8ajm`}
                                            searched={true}
                                            searchsAd={
                                                <ConditionNum ecId={`${this && this.props && this.props.ecId || ''}_ConditionNum@q09c6q`} listStore={taskStore} type="task" formB={formB} col={2} onEnterSearch={(visible) => { this.setState({ visible }); setSearchPanelVisible(visible); initSearchPanel() }}></ConditionNum>
                                            }
                                            buttonsAd={this.getSearchButtons()}
                                            visible={visible}
                                            onVisibleChange={(visible) => { this.setState({ visible }); setSearchPanelVisible(visible); initSearchPanel() }}
                                        />
                                    </div>
                                    <div style={{ float: 'right', marginRight: '100px' }}>
                                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0kaeli`} type="primary" className="g-task-taskMain-serach" onClick={this.doexport}>{getLabel(17416, "导出")}</Button>
                                    </div>
                                    {/* <div style={{ clear: 'both' }}>
                                    </div> */}
                                </div>
                                <div>

                                    {
                                    //    (!tableTaskStore.loading && toJS(tableTaskStore).columns.length>0 ) && //xk:解决无数据不显示列头问题(可以删除，因为其内部自己处理了自带loading)
                                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@okxnnh`}
                                            dragColumns='0'
                                            comsWeaTableStore={tableTaskStore}
                                            childrenColumnName="subListspan"
                                            hasOrder={true}
                                            //needScroll={true}
                                            getColumns={c => this.reRenderColumns(c)}
                                            onOperatesClick={this.onOperatesClick.bind(this)}
                                            tableWidth={(columns) => this.tableWidth(columns)}
                                            scroll={columnsNum <= 10 ? { x: 0, y: tablescroll } : { x: 100 * columnsNum, y: tablescroll }}
                                            //scroll={{ x: scrollWidth }}
                                        />
                                    }

                                </div>
                                <div>
                                    <WeaSlideModal ecId={`${this && this.props && this.props.ecId || ''}_WeaSlideModal@erd8gs`} visible={showSlideModal}
                                        top={5}
                                        width={40}
                                        height={400}
                                        direction={'right'}
                                        measure={'%'}
                                        content={(showSlideModal && <TaskSlide ecId={`${this && this.props && this.props.ecId || ''}_TaskSlide@oc8del`} taskSlideStore={taskStore} doAction={this.doAction} id={taskStore.slideStatu.id} showTaskSlide={showSlideModal} />)}
                                        onClose={() => taskStore.showSlideModal(false, id)}
                                    />
                                </div>
                                <div>
                                    <Model ecId={`${this && this.props && this.props.ecId || ''}_Model@schx5p`} modelType={modelType} id={id} contentStore={taskStore} pathname={pathname} search={search} routepath={path}></Model>
                                </div>
                                <div>
                                    <ModalConfirm ecId={`${this && this.props && this.props.ecId || ''}_ModalConfirm@5g7tmi`} modelType={modelType} id={id} content={content} confirmStore={taskStore}></ModalConfirm>
                                </div>
                                {/*    <div className="g-task-taskMain-kongbai" style={{ width: "100%", height: "100%" }} onClick={() => {taskStore.showSlideModal(false,id)}}></div> */}
                            </WeaLeftRightLayout>
                        </WeaTop>
                    </WeaRightMenu>
                </div>
            </div>
        )
    }
    /* 高级搜索操作按钮组 */
    getSearchButtons() {
        const { taskStore } = this.props;
        const { clearFormFields } = taskStore;
        const btnStyle = { borderRadius: 3, width: 80 }
        return [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h2kuin@search`} type="primary" style={btnStyle} onClick={this.forwardQueryResult.bind(this)}>{getLabel(197, "搜索")}</Button>),
            (<span style={{ width: '15px', display: 'inline-block' }}></span>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gl3e5z@reset`} type="ghost" style={btnStyle} onClick={() => { taskStore.clearFormFields() }}>{getLabel(2022, "重置")}</Button>),
            (<span style={{ width: '15px', display: 'inline-block' }}></span>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d1ko29@cancel`} type="ghost" style={btnStyle} onClick={() => { this.cancel() }}>{getLabel(201, "取消")}</Button>)
        ]
    }
    /* 搜索面板搜索方法 */
    forwardQueryResult() {
        const { taskStore } = this.props;
        const { selectedTreeKey, setSearchPanelVisible } = taskStore;
        taskStore.doSearch({ fromSuperPage: true, "categoryid": selectedTreeKey, "isSuperSearch": true })
        this.setState({ visible: false })
        setSearchPanelVisible(this.state.visible)
    }
    /* 高级搜索取消方法 */
    cancel() {
        this.setState({ visible: false });
        this.props.taskStore.setSearchPanelVisible(this.state.visible);
    }
    /**
     * 重定列各列属性
     * @param {*} columns
     */
    reRenderColumns(columns) {
        const { taskStore: { getcolumnsNum } } = this.props;
        const { dataType, getTaskRight, hasTaskRight } = this.props.taskStore;
        let columnsIndex = 0;
        //我的主办时重定义列
        //19.3.8 lusx 当列过多时,才显示横向滚动条
        columns.forEach(c => {
            if (c.display === "true") {
                columnsIndex = columnsIndex + 1;
            }
            if (dataType == 4) {
                if (c.dataIndex == 'name') {
                    const cc = (id) => {
                        getTaskRight(
                            { "id": parseInt(id) },
                            result => {
                                const { taskStore } = this.props;
                                const { slideStatu } = taskStore;
                                if (id !== slideStatu.id && this.props.taskStore.hasTaskRight) {
                                    taskStore.formSlide = new WeaForm();
                                    taskStore.clearSlide();
                                    taskStore.getSlideCondition({ id: id });
                                    taskStore.showSlideModal(true, id);
                                }
                            }

                        );
                    }
                    c.render = function (text, record) {
                        return (<span className='wea-prj-progressStyle' onClick={() => { cc(record.id) }}>
                            <a>{record.sKeyFlagspan === "1" ? <span className="g-top-cui">{common.URGE}</span> : null}{text}</a>
                        </span>)
                    }
                }
            }
            if (c.dataIndex == 'progress') {
                c.render = function (text, record) {
                    return <span className='wea-prj-progressStyle' >
                        <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@iyanlo@${c.dataIndex}`} percent={record.progress || 0} />
                    </span>
                }
            } else if (c.dataIndex == 'status') {
                c.render = function (text, record) {
                    return <span >
                        <GovernTag ecId={`${this && this.props && this.props.ecId || ''}_GovernTag@ts1d3u`} record={record} />
                    </span>
                }
            } else if (c.dataIndex == 'feedstatus') {
                c.render = function (text, record) {
                    return <span >
                        <GovernLight ecId={`${this && this.props && this.props.ecId || ''}_GovernLight@35bilo`} record={record} showType="feedback" />
                    </span>
                }
            } else if (c.dataIndex == 'enddate') {
                c.render = function (text, record) {
                    return <span>
                        <GovernBadge ecId={`${this && this.props && this.props.ecId || ''}_GovernBadge@tyhuzm`} record={record} text={text} />
                    </span>
                }
            } else if (c.dataIndex == 'name' && dataType != 4) {
                c.render = function (text, record) {
                    let hrefText = `javaScript:hrefTaskInfo(${record.id});`
                    return <span>
                        <a href={hrefText} target="_self">{record.sKeyFlagspan === "1" ? <span className="g-top-cui">{common.URGE}</span> : null}{text}</a>
                    </span>
                }
            }
        })
        getcolumnsNum(columnsIndex+4);
        return columns;
    }
    /**
     * 按钮点击事件(每列扩展按钮)
     * @param {*} record
     * @param {*} index
     * @param {*} operate
     * @param {*} flag
     */
    onOperatesClick(record, index, operate, flag) {
        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:", "");
        fn = fn.substring(0, fn.indexOf('('));
        if (fn != "") {
            this.doAction(fn.replace("fn", ""), record);
        }
    }
    tableWidth(columns) {
        // const columnLength = columns.filter((col)=>col.display === 'true').length;
        // console.log("columnLength",columnLength)
        // if(columnLength>10){
        //   return columnLength*200;
        // }else{
        //   return '100%'
        // }
    }

    /**
     * 接口执行方法
     */
    doAction = (fn, record) => {
        const { taskStore } = this.props;
        let id = record.id;
        if (BtnType.checkShowModel(fn)) {
            taskStore.getActionSetting(id, fn);
        } else if (BtnType.checkShowConfirm(fn)) {
            taskStore.showconfirm(id, fn, BtnType.getTitle(fn), BtnType.getContent(fn));
        } else {
            taskStore.modelStore.subBtn(fn, id);
        }
    }
    /*
     * 顶部搜索，select的key值改变，执行方法
    */
    handleChange(data) {
        if (Object.keys(data)[0] == "selectKey") {
            const { taskStore } = this.props;
            taskStore.handleChange();
        }
    }
    getRightMenu() {
        let btns = [];
        btns.push({
            key: "search",
            icon: <i className='icon-coms-search' />,
            content: getLabel(197, "搜索"),
            onClick: this.doSearch.bind(this)
        });
        btns.push({ key: "export", icon: <i className='icon-coms-export' />, content: getLabel(17416, '导出', 'label'), onClick: () => this.doexport() });
        return btns;
    }
    doSearch() {
        const { taskStore } = this.props;
        const { selectedTreeKey } = taskStore;
        //设置dataType
        // const preDataType = this.props.location.query.dataType;
        taskStore.setDataType(0);
        let params = { "isSuper": "0", "isSuperPage": false, "isSelect": taskStore.isSelect, "fromSuperPage": false, "selectedTreeKey": 0 }
        taskStore.doSearch({ ...params })
    }

    doexport = () => {
        const { taskStore } = this.props;
        let selectedIds = toJS(taskStore.tableTaskStore.selectedRowKeysAllPages);
        const { selectedTreeKey } = taskStore
        if (selectedIds.length == 0) {
            message.warning(getLabel(501159, '请选择要操作的数据'));
        } else {
            taskStore.exportGovernExcel(selectedIds, "27", getLabel(17416, "导出"), getLabel('508054', "确认要导出吗？"), selectedTreeKey, '4');
        }

    }
}

export default taskMain0;
